<template>
  <div class="inner-container">
    <br>
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
      <el-form-item label="原密码" prop="rawPassword">
        <el-input v-model="formData.rawPassword" type="password" show-password placeholder="请输入原密码"/>
      </el-form-item>
      <el-form-item label="新密码" prop="newPassword">
        <el-input v-model="formData.newPassword" type="password" show-password placeholder="请输入新密码"/>
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input v-model="formData.confirmPassword" type="password" show-password placeholder="请输入确认密码"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit">修改</el-button>
        <el-button @click="formRef.resetFields()">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import {ref} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import router from "@/router"
import request from "@/utils/request"

const formRef = ref()
const formData = ref({
  rawPassword: undefined,
  newPassword: undefined,
  confirmPassword: undefined
})
const formRules = ref({
  rawPassword: [
    {required: true, message: '原密码为必填项'},
    {min: 6, max: 20, message: '长度在 6 到 20 个字符'}
  ],
  newPassword: [
    {required: true, message: '新密码为必填项'},
    {min: 6, max: 20, message: '长度在 6 到 20 个字符'},
    {
      validator: (rule, value, callback) => value === formData.value.rawPassword ? callback(new Error()) : callback(),
      message: "新密码不能与原密码相同"
    }
  ],
  confirmPassword: [
    {required: true, message: '确认密码为必填项'},
    {
      validator: (rule, value, callback) => value !== formData.value.newPassword ? callback(new Error()) : callback(),
      message: "两次输入的密码不一致"
    }
  ]
})

const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (!valid) {
      ElMessage.error('请正确填写参数')
      return
    }
    request.patch('/api/sys/users/profile/password', formData.value)
        .then(res => {
          ElMessageBox.alert('修改成功，请重新登录~', '提示', {
            type: 'success',
            showClose: false,
            confirmButtonText: '确定'
          }).then(() => {
            localStorage.clear()
            router.push('/login')
          })
        })
  })
}
</script>

<style scoped>

</style>
